<template>
  <v-container class="mb-15">
    <!--      添加评论-->
    <v-row v-if="showAddComment">
      <v-col cols="12">
        <v-card>
          <v-row class="px-4">
            <v-col cols="auto">
              <span class="text-subtitle-1">添加评论</span>
            </v-col>
            <v-col cols="auto" class="ml-auto">
              <v-btn small @click="$emit('closeAddComment')">取消</v-btn>
              <v-btn small color="primary" class="ml-1" @click="doCommitComment()">确定</v-btn>
            </v-col>
          </v-row>
          <v-card-text class="pb-0">
            <v-textarea
                ref="content"
                outlined
                auto-grow
                counter="100"
                :rules="[rules.required,rules.maxLength(100)]"
                v-model="newCommentContentRaw"
            ></v-textarea>

          </v-card-text>
          <v-card-actions v-if="commentType==='production'" class="pt-0 px-4">
            打个分吧：
            <v-spacer></v-spacer>
            <span class="grey--text text-caption mr-2">
              ({{ newCommentForm.score }})
            </span>
            <v-rating
                background-color="yellow accent-4"
                color="yellow accent-4"
                dense
                half-increments
                hover
                v-model="newCommentForm.score"
                size="18">
            </v-rating>
          </v-card-actions>
          <v-card-text class="pt-0">
            <my-image-upload :image-size="imageSize" @onUpdate="setImg" ref="uploader">

            </my-image-upload>
          </v-card-text>
        </v-card>
      </v-col>
    </v-row>
    <!--      用户评论-->
    <v-row v-for="item in comments" :key="item.cid">
      <v-col cols="2" class="text-center">
        <v-avatar @click="$router.push('/userInfo/'+item.uid)">
          <v-img v-if="getAvatarPath(item.avatar)" :src="getAvatarPath(item.avatar)"></v-img>
        </v-avatar>
      </v-col>
      <v-col cols="10">
        <v-row>
          <v-col cols="8" class="pb-0 pt-1">
            <span class="text-subtitle-1">{{ item.nickname }}</span>
          </v-col>
          <!--            菜单按钮-->
          <v-col cols="4" class="pb-0 pt-1 text-right">
            <v-menu offset-y>
              <template v-slot:activator="{ on, attrs }">
                <v-btn
                    small
                    icon
                    v-bind="attrs"
                    v-on="on"
                >
                  <v-icon class="lighten-4">mdi-dots-vertical</v-icon>
                </v-btn>
              </template>
              <v-list dense>
                <v-list-item dense @click="doGoReport(item.cid)">
                  <v-list-item-title>投诉</v-list-item-title>
                </v-list-item>
                <v-list-item v-if="item.uid===$store.state.uid" dense @click="deleteComment(item)">
                  <v-list-item-title>删除</v-list-item-title>
                </v-list-item>
              </v-list>
            </v-menu>
          </v-col>
          <v-col cols="12" class="text-caption py-0">
            {{ item.description }}
          </v-col>
          <v-col cols="12" class=" py-0"  v-if="commentType==='production'">
            <v-rating
                readonly
                background-color="yellow accent-4"
                color="yellow accent-4"
                dense
                half-increments
                hover
                :value="parseFloat(item.score)"
                size="18">

            </v-rating>
          </v-col>
          <v-col cols="12" class="py-2 text-subtitle-2">
            {{ item.content }}
          </v-col>
          <!--          评论详情中的 图片-->
          <v-col cols="12" v-if="item.pics.length > 0" class="text-left">
            <v-img
                v-for="(pic,i) in item.pics"
                :src="baseUrl+imgPrefixUrl+pic"
                :width="picScale"
                :height="picScale"
                class="d-inline-block ma-1"
                :key="i"
                @click="showImage(pic,false)"
            ></v-img>
          </v-col>

          <v-col cols="6" class="py-0 text-caption">
            {{ item.createTime }}
          </v-col>
          <v-col cols="6" class="py-0 text-caption text-right">
            <v-icon color="primary" v-if="item.approved" @click="cancelApprove(item)">mdi-thumb-up</v-icon>
            <v-icon v-else @click="doApprove(item)">mdi-thumb-up-outline</v-icon>
            {{ item.approveCount }}
          </v-col>
        </v-row>
      </v-col>
    </v-row>
    <load-more :loading="loadingComments" v-if="loadingMore" @onLoadMore="loadMoreComment"></load-more>
    <v-card-subtitle class="text-center pt-0" v-if="comments.length===0">来写一条评论吧~</v-card-subtitle>
    <loading :msg="committingMsg" v-if="committing"></loading>
    <show-big-image :src="bigImgSrc" :show="showBigImg" @dismiss="showBigImg = false"></show-big-image>
    <new-report :show="isShowNewReport" :id="newReportId" type="article" @dismiss="isShowNewReport=false" @toast="$emit('toast', $event)"></new-report>
  </v-container>
</template>

<script>
import Loading from "./Loading";
import MyImageUpload from "./MyImageUpload";
import LoadMore from "./LoadMore";
import ShowBigImage from "./ShowBigImage";
import NewReport from "./NewReport";
import {printMsg, rules, utf8_to_b64, b64_to_utf8, myDateFormat} from "../util/util";
import {baseUrl, imageSize, imgPrefixUrl} from "../myConfig";

export default {
  name: "Comments",
  components: {NewReport, Loading, MyImageUpload, LoadMore, ShowBigImage},
  props:{
    showAddComment:{
      default:false,
      type:Boolean
    },
    commentType:{
      type:String,
      required:true,
      validator: function (value) {
        return ['production', 'article'].indexOf(value) !== -1
      }
    },
    id:{
      type:String,
      required: true
    }
  },

  data: () => ({
    baseUrl:baseUrl,
    imgPrefixUrl:imgPrefixUrl,
    imageSize: imageSize,
    rules: rules,
    newCommentContentRaw: '',
    newCommentForm: {
      aid: '',
      uid: '',
      content: '',
      score: 5,
      pics: [],
    },
    committingMsg: '正在提交...',
    committing: false,

    loadingComments: false,
    loadingMore: true,

    subscribed: true,

    page: 1,
    row: 10,

    comments: [],
    bigImgSrc:'',
    showBigImg:false,

    picScale: 95,

    isShowNewReport:false,
    newReportId:'',
  }),
  methods: {
    showImage(src,raw=false){
      if (!raw){
        src = baseUrl+imgPrefixUrl+src;
      }
      this.bigImgSrc = src;
      this.showBigImg=true;
    },
    setImg(imgs) {
      this.newCommentForm.pics = imgs.new
      printMsg(imgs,this)
    },
    doCommitComment() {
      if (!this.$refs['content'].validate(true)) {
        return
      }
      this.newCommentForm.content = utf8_to_b64(this.newCommentContentRaw)
      this.committing = true
      // 上传图片
      if (this.newCommentForm.pics.length > 0) {
        let data = {base64Files: this.newCommentForm.pics}
        this.$http.post('file/saveImages', data).then(res => {
          printMsg(res,this)
          if (this.newCommentForm.pics) this.newCommentForm.pics = res.data.map(a => a.fileName).join(',')
          this.saveComment()
        }).catch(res => {
          this.committing = false
          this.$emit('toast', res.msg)
        })
      } else {
        // 解决无图片上传时 为 [] 的问题
        this.newCommentForm.pics=''
        this.saveComment()
      }

    },
    saveComment() {
      this.newCommentForm.aid = this.id
      this.newCommentForm.uid = this.$store.state.uid
      let data = this.newCommentForm
      this.$http.post('comment/addComment', data).then(res => {
        this.$emit('toast', "评论成功")
        // 清理内容
        this.committing = false
        this.$emit('closeAddComment')
        this.newCommentForm.content = ''
        this.newCommentForm.pics = []
        this.newCommentForm.score = 5
        this.newCommentContentRaw = ''
        this.$refs['uploader'].clear()
        this.loadComments()
      }).catch(res => {
        this.committing = false
        this.$emit('toast', res.msg)
      })
    },

    loadMoreComment() {
      this.loadingComments = true;
      this.page += 1
      this.loadComments()
    },
    loadComments() {
      let data = {
        currentUid:this.$store.state.uid,
        type: this.commentType,
        aid: this.id,
        page: 1,
        row: this.row * this.page
      }
      printMsg(this.row,this)
      printMsg(data,this)
      this.loadingMore = true
      this.$http.post('comment/listComment', data).then(res => {
        printMsg(res.data,this)
        if (res.data) {

          res.data = res.data.map(a => Object.assign(a, a.user))
          this.comments = res.data.map(a => {
            a.content = b64_to_utf8(a.content);
            a.createTime = myDateFormat(a.createTime);
            a.pics? a.pics = a.pics.split(','):[]
            return a
          })
          if (res.total === this.comments.length) {
            this.loadingMore = false
          }
          this.$emit('updateCommentsCount',res.total)
        }
        this.loadingMore = false
        this.loadingComments = false
      }).catch(res => {
        this.$emit('toast', res.msg)
      })
    },
    getAvatarPath(filename) {
      if (filename) {
        return baseUrl + imgPrefixUrl + filename
      } else {
        return ''
      }
    },
    doApprove(comment){
      let data = {
        fromUid:this.$store.state.uid,
        toAid:comment.cid,
        type:'comment'
      }
      this.$http.post('approve/doApprove', data).then(res => {
        comment.approved = true
        comment.approveCount+=1
        this.$emit('toast','点赞成功')
      }).catch(res => {
        this.$emit("toast", res.msg)
      })
    },
    cancelApprove(comment){
      let data = {
        fromUid:this.$store.state.uid,
        toAid:comment.cid,
        type:'comment'
      }
      this.$http.post('approve/cancelApprove', data).then(res => {
        comment.approved = false
        comment.approveCount-=1
        this.$emit('toast','取消点赞成功')
      }).catch(res => {
        this.$emit("toast", res.msg)
      })
    },
    deleteComment(comment){
      let data = {cid:comment.cid}
      this.$http.post('comment/deleteComment', data).then(res => {
        this.loadComments()
        this.$emit('toast','删除评论成功')
      }).catch(res => {
        this.$emit('toast', res.msg)
      })
    },
    doGoReport(cid){
      this.isShowNewReport=true
      this.newReportId = cid
    }
  },
  computed: {},
  beforeMount() {
    this.newCommentForm.type = this.commentType
    this.newCommentForm.aid = this.id

    this.loadComments()
  }

}
</script>

<style scoped>

</style>
